<template>
  <van-popup v-model:show="visible" position="bottom" :style="{ height: '100%' }" :close-on-click-overlay="false"
    @close="handleClose">
    <div class="login-register-overlay">
      <!-- 登录模块 -->
      <div class="login-module" v-if="showLoginModule">
        <div class="close" @click="hideLogin">
          <van-icon name="arrow-left" />
        </div>
        <div class="login-img">
          <img src="../assets/img/login-bg.png" alt="" />
        </div>
        <div class="login-title">
          <span>{{ isPasswordLogin ? '密码登录' : '手机号验证码登录' }}</span>
          <span v-show="!isPasswordLogin">短信验证后自动登录</span>
        </div>

        <div class="login-input">
          <div class="phone-number">
            <van-icon name="phone-o" class="input-icon" />
            <input type="text" placeholder="手机号码" v-model="phoneNumber" @input="handlePhoneInput" maxlength="11" />
          </div>
          <div class="verification-code">
            <van-icon :name="isPasswordLogin ? 'lock' : 'chat-o'" class="input-icon" />
            <div class="error-tip" v-if="codeErrorTip">{{ codeErrorTip }}</div>
            <input :type="isPasswordLogin ? (showPassword ? 'text' : 'password') : 'text'"
              :placeholder="isPasswordLogin ? '请输入密码' : '短信验证码'" v-model="verificationCode" @input="handleCodeInput"
              :autocomplete="isPasswordLogin ? 'current-password' : 'off'" maxlength="6" />
            <div class="send-code" :class="{ disabled: isCodeCountdowning }" v-show="!isPasswordLogin"
              @click="sendVerificationCode('login')">
              {{ codeCountdown > 0 ? `${codeCountdown}秒` : '发送验证码' }}
            </div>
            <van-icon v-if="isPasswordLogin" :name="showPassword ? 'eye-o' : 'closed-eye'" class="show-password"
              @click="togglePasswordVisibility" />
          </div>
        </div>

        <div class="agreement-module">
          <div class="circle" :class="{ active: agreementActive }" @click="toggleAgreement">
            <van-icon v-if="agreementActive" name="success" size="12" />
          </div>
          我已阅读并同意
          <span>《用户服务协议》</span>
          和
          <span>《隐私政策》</span>
        </div>

        <button class="login-btn" :style="{ backgroundColor: canLogin ? '#000' : '#ccc' }" :disabled="!canLogin"
          @click="login">
          登录
        </button>
        <div class="login-options">
          <span class="password-login" @click="toggleLoginType">
            {{ isPasswordLogin ? '验证码登录' : '密码登录' }}
          </span>
          <span class="register" @click="showRegisterModule">注册</span>
        </div>
      </div>

      <!-- 注册模块 -->
      <div class="register-module" v-if="isRegisterModuleVisible">
        <div class="close" @click="hideRegister">
          <van-icon name="arrow-left" />
        </div>
        <div class="register-img">
          <img src="../assets/img/login-img.png" alt="" />
        </div>
        <div class="register-title">
          <span>注册账号</span>
          <span>短信验证后自动登录</span>
        </div>

        <div class="register-input">
          <div class="phone-number">
            <van-icon name="phone-o" class="input-icon" />
            <input type="text" placeholder="手机号码" v-model="registerPhone" @input="handleRegisterPhoneInput"
              maxlength="11" />
          </div>

          <div class="verification-code">
            <van-icon name="chat-o" class="input-icon" />
            <input type="text" placeholder="短信验证码" v-model="registerCode" @input="handleRegisterCodeInput"
              maxlength="6" />
            <div class="send-code" :class="{ disabled: isRegisterCodeCountdowning }"
              @click="sendVerificationCode('register')">
              {{
                registerCodeCountdown > 0
                  ? `${registerCodeCountdown}秒`
                  : '发送验证码'
              }}
            </div>
          </div>
          <div class="password-input">
            <van-icon name="lock" class="input-icon" />
            <input :type="showRegisterPassword ? 'text' : 'password'" placeholder="设置密码" v-model="registerPassword"
              autocomplete="new-password" @input="handleRegisterPasswordInput" />
            <van-icon :name="showRegisterPassword ? 'eye-o' : 'closed-eye'" class="show-password"
              @click="toggleRegisterPasswordVisibility" />
          </div>
        </div>

        <div class="agreement-module">
          <div class="circle" :class="{ active: agreementActive }" @click="toggleAgreement">
            <van-icon v-if="agreementActive" name="success" size="12" />
          </div>
          我已阅读并同意
          <span>《用户服务协议》</span>
          和
          <span>《隐私政策》</span>
        </div>

        <button class="register-btn" :style="{ backgroundColor: canRegister ? '#000' : '#ccc' }"
          :disabled="!canRegister" @click="register">
          注册
        </button>
      </div>

      <!-- 密码设置对话框 -->
      <van-dialog v-model:show="showPasswordDialog" title="您是新用户，请设置您的账号密码" :show-confirm-button="true"
        :show-cancel-button="false" confirm-button-text="确认" @confirm="confirmPassword">
        <div class="password-dialog-content">
          <div class="password-input-wrapper">
            <input :type="showDialogPassword ? 'text' : 'password'" v-model="dialogPassword" placeholder="请输入密码（至少6位）"
              autocomplete="new-password" class="password-dialog-input" />
            <van-icon :name="showDialogPassword ? 'eye-o' : 'closed-eye'" class="password-toggle-icon"
              @click="toggleDialogPassword" />
          </div>
        </div>
      </van-dialog>
    </div>
  </van-popup>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { showToast } from 'vant'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()

// 显示状态
const visible = ref(false)
const showLoginModule = ref(false)
const isRegisterModuleVisible = ref(false)
const isPasswordLogin = ref(false)
const showPassword = ref(false)
const showRegisterPassword = ref(false)
const agreementActive = ref(false)

// 表单数据
const phoneNumber = ref('')
const verificationCode = ref('')
const registerPhone = ref('')
const registerCode = ref('')
const registerPassword = ref('')
const codeErrorTip = ref('')

// 验证码倒计时
const codeCountdown = ref(0)
const isCodeCountdowning = ref(false)
const registerCodeCountdown = ref(0)
const isRegisterCodeCountdowning = ref(false)

// 密码对话框
const showPasswordDialog = ref(false)
const dialogPassword = ref('')
const showDialogPassword = ref(false)
let passwordDialogResolve: ((value: string) => void) | null = null

// 路由路径记录
const currentRoutePath = ref('')

// 计算属性
const isPhoneValid = computed(() => {
  const phoneRegex = /^1\d{10}$/
  return phoneRegex.test(phoneNumber.value.trim())
})

const isCodeValid = computed(() => {
  return verificationCode.value.trim() !== ''
})

const canLogin = computed(() => {
  return (
    agreementActive.value &&
    isPhoneValid.value &&
    isCodeValid.value
  )
})

const isRegisterPhoneValid = computed(() => {
  const phoneRegex = /^1\d{10}$/
  return phoneRegex.test(registerPhone.value.trim())
})

const isRegisterCodeValid = computed(() => {
  return registerCode.value.trim() !== ''
})

const isRegisterPasswordValid = computed(() => {
  return registerPassword.value.trim().length >= 6
})

const canRegister = computed(() => {
  return (
    agreementActive.value &&
    isRegisterPhoneValid.value &&
    isRegisterCodeValid.value &&
    isRegisterPasswordValid.value
  )
})

// 方法
const show = (routePath?: string) => {
  currentRoutePath.value = routePath || router.currentRoute.value.path
  visible.value = true
  showLoginModule.value = true
  isRegisterModuleVisible.value = false
  resetForm()
}

const hide = () => {
  visible.value = false
}

const handleClose = () => {
  hide()
}

const resetForm = () => {
  phoneNumber.value = ''
  verificationCode.value = ''
  registerPhone.value = ''
  registerCode.value = ''
  registerPassword.value = ''
  agreementActive.value = false
  codeErrorTip.value = ''
  isPasswordLogin.value = false
}

const sendVerificationCode = (type: 'login' | 'register') => {
  const phoneValid =
    type === 'login' ? isPhoneValid.value : isRegisterPhoneValid.value

  if (!phoneValid) {
    showToast({
      message: '请输入正确的手机号码',
      position: 'top',
    })
    return
  }

  const code = Math.floor(100000 + Math.random() * 900000).toString()
  userStore.setVerificationCode(code)

  showToast({
    message: `验证码：${code}`,
    position: 'top',
    duration: 5000,
  })

  if (type === 'login') {
    isCodeCountdowning.value = true
    codeCountdown.value = 60
    const timer = setInterval(() => {
      codeCountdown.value--
      if (codeCountdown.value <= 0) {
        clearInterval(timer)
        isCodeCountdowning.value = false
      }
    }, 1000)
  } else {
    isRegisterCodeCountdowning.value = true
    registerCodeCountdown.value = 60
    const timer = setInterval(() => {
      registerCodeCountdown.value--
      if (registerCodeCountdown.value <= 0) {
        clearInterval(timer)
        isRegisterCodeCountdowning.value = false
      }
    }, 1000)
  }
}

const toggleLoginType = () => {
  isPasswordLogin.value = !isPasswordLogin.value
  codeErrorTip.value = ''
  verificationCode.value = ''
}

const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

const toggleAgreement = () => {
  agreementActive.value = !agreementActive.value
}

const hideLogin = () => {
  hide()
}

const showRegisterModule = () => {
  if (!agreementActive.value) {
    showToast({
      message: '登录/注册前请阅读并同意相关协议',
      position: 'top',
    })
    return
  }
  isRegisterModuleVisible.value = true
  showLoginModule.value = false
}

const hideRegister = () => {
  isRegisterModuleVisible.value = false
  showLoginModule.value = true
}

const toggleRegisterPasswordVisibility = () => {
  showRegisterPassword.value = !showRegisterPassword.value
}

const handlePhoneInput = () => {
  // 验证输入
}

const handleCodeInput = () => {
  codeErrorTip.value = ''
}

const handleRegisterPhoneInput = () => {
  // 验证输入
}

const handleRegisterCodeInput = () => {
  // 验证输入
}

const handleRegisterPasswordInput = () => {
  // 验证输入
}

const login = async () => {
  if (!canLogin.value) return

  if (isPasswordLogin.value) {
    const users = JSON.parse(localStorage.getItem('users') || '[]')
    const user = users.find((u: any) => u.phoneNumber === phoneNumber.value)

    if (user && user.password === verificationCode.value) {
      localStorage.setItem('isLoggedIn', 'true')
      localStorage.setItem('currentPhoneNumber', phoneNumber.value)
      showToast({
        message: '登录成功',
        position: 'top',
      })
      hide()
      handleLoginSuccess()
    } else {
      showToast({
        message: '账号或密码错误',
        position: 'top',
      })
    }
    return
  }

  codeErrorTip.value = ''

  if (verificationCode.value !== userStore.verificationCode) {
    codeErrorTip.value = '验证码错误'
    return
  }

  const users = JSON.parse(localStorage.getItem('users') || '[]')
  const user = users.find((u: any) => u.phoneNumber === phoneNumber.value)

  if (user) {
    localStorage.setItem('isLoggedIn', 'true')
    localStorage.setItem('currentPhoneNumber', phoneNumber.value)
    showToast({
      message: '登录成功',
      position: 'top',
    })
    hide()
    userStore.clearVerificationCode()
    handleLoginSuccess()
  } else {
    const password = await openPasswordDialog()
    if (!password) return

    const defaultNickname = getDefaultNickname(phoneNumber.value)
    const newUser = {
      phoneNumber: phoneNumber.value,
      password: password,
      nickname: defaultNickname,
    }
    users.push(newUser)
    localStorage.setItem('users', JSON.stringify(users))

    localStorage.setItem('isLoggedIn', 'true')
    localStorage.setItem('currentPhoneNumber', phoneNumber.value)
    showToast({
      message: '注册并登录成功',
      position: 'top',
    })
    hide()
    userStore.clearVerificationCode()
    handleLoginSuccess()
  }
}

const openPasswordDialog = (): Promise<string> => {
  return new Promise((resolve) => {
    dialogPassword.value = ''
    showDialogPassword.value = false
    passwordDialogResolve = resolve
    showPasswordDialog.value = true
  })
}

const toggleDialogPassword = () => {
  showDialogPassword.value = !showDialogPassword.value
}

const confirmPassword = () => {
  if (dialogPassword.value.trim().length < 6) {
    showToast({
      message: '密码长度至少6位',
      position: 'top',
    })
    return
  }

  if (passwordDialogResolve) {
    passwordDialogResolve(dialogPassword.value.trim())
    passwordDialogResolve = null
  }
  showPasswordDialog.value = false
}

const register = () => {
  if (!canRegister.value) return

  if (registerCode.value !== userStore.verificationCode) {
    showToast({
      message: '验证码错误',
      position: 'top',
    })
    return
  }

  const users = JSON.parse(localStorage.getItem('users') || '[]')
  const existingUser = users.find(
    (u: any) => u.phoneNumber === registerPhone.value
  )
  if (existingUser) {
    showToast({
      message: '该手机号已注册',
      position: 'top',
    })
    return
  }

  const defaultNickname = getDefaultNickname(registerPhone.value)
  const newUser = {
    phoneNumber: registerPhone.value,
    password: registerPassword.value,
    nickname: defaultNickname,
  }
  users.push(newUser)
  localStorage.setItem('users', JSON.stringify(users))

  localStorage.setItem('isLoggedIn', 'true')
  localStorage.setItem('currentPhoneNumber', registerPhone.value)
  showToast({
    message: '注册成功',
    position: 'top',
  })
  hide()
  userStore.clearVerificationCode()
  handleLoginSuccess()
}

const getDefaultNickname = (phoneNumber: string) => {
  const lastFour = phoneNumber.slice(-4)
  return `用户${lastFour}`
}

const handleLoginSuccess = () => {
  // 触发登录成功事件
  window.dispatchEvent(new CustomEvent('loginSuccess'))

  // 如果不在"我的"页面，则跳转到首页
  if (currentRoutePath.value !== '/my') {
    router.push('/')
  }
}

// 监听全局事件
const handleShowLogin = (event: Event) => {
  const customEvent = event as CustomEvent
  show(customEvent.detail?.routePath)
}

onMounted(() => {
  window.addEventListener('showLoginRegister', handleShowLogin)
})

onUnmounted(() => {
  window.removeEventListener('showLoginRegister', handleShowLogin)
})

// 暴露方法供外部调用
defineExpose({
  show,
  hide,
})
</script>

<style scoped lang="less">
.login-register-overlay {
  width: 100vw;
  height: 100vh;
  background-color: #fff;
  position: relative;
  overflow-y: auto;
}

.login-module,
.register-module {
  width: 100vw;
  min-height: 100vh;
  background-color: #fff;
  position: relative;

  .close {
    position: absolute;
    top: 20px;
    left: 20px;
    font-size: 12px;
    cursor: pointer;
    z-index: 1;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    background-color: rgba(0, 0, 0, 0.3);
    border-radius: 50%;
  }

  .login-img,
  .register-img {
    margin-bottom: 10px;

    img {
      width: 100%;
      display: block;
      height: auto;
    }
  }

  .login-title,
  .register-title {
    display: flex;
    flex-direction: column;
    padding: 0 5vw;
    box-sizing: border-box;
    margin-top: 20px;
    margin-bottom: 30px;

    span:nth-child(1) {
      font-size: 10px;
      line-height: 14px;
      margin-bottom: 5px;
    }

    span:nth-child(2) {
      font-size: 8px;
      color: #cdcdcd;
    }
  }

  .login-input,
  .register-input {
    padding: 0 5vw;
    box-sizing: border-box;

    input {
      width: 80%;
      border: none;
      outline: none;
      font-size: 10px;
      background: transparent;
    }

    .phone-number,
    .verification-code,
    .password-input {
      display: flex;
      align-items: center;
      width: 100%;
      padding: 5px 0;
      border-bottom: 1px solid #cdcdcd;
      position: relative;
      margin-bottom: 10px;

      .input-icon {
        font-size: 18px;
        color: #999;
        margin-right: 8px;
      }

      // 隐藏浏览器默认的密码显示按钮
      input[type="password"] {
        &::-webkit-credentials-auto-fill-button {
          display: none !important;
          visibility: hidden;
          pointer-events: none;
          opacity: 0;
          position: absolute;
          right: -9999px;
        }

        &::-webkit-strong-password-auto-fill-button {
          display: none !important;
          visibility: hidden;
          pointer-events: none;
          opacity: 0;
          position: absolute;
          right: -9999px;
        }

        // 针对 Edge 浏览器
        &::-ms-reveal {
          display: none !important;
        }

        &::-ms-clear {
          display: none !important;
        }
      }

      .send-code {
        position: absolute;
        right: 5px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 10px;
        cursor: pointer;
        color: #000;
        transition: color 0.3s ease;

        &.disabled {
          color: #999;
          cursor: not-allowed;
        }
      }

      .error-tip {
        position: absolute;
        top: -20px;
        left: 0;
        font-size: 10px;
        color: #ff4444;
      }

      .show-password {
        position: absolute;
        right: 5px;
        top: 50%;
        transform: translateY(-50%);
        cursor: pointer;
        color: #999;
      }
    }
  }

  >.agreement-module {
    margin-top: 35px;
  }

  .login-btn,
  .register-btn {
    margin-left: 5vw;
    width: 90vw;
    border: none;
    height: 4vh;
    border-radius: 8px;
    margin-top: 15px;
    margin-bottom: 10px;
    background-color: #aaa;
    color: #fff;
    font-size: 10px;
    transition: background-color 0.3s ease;
    cursor: pointer;

    &:disabled {
      cursor: not-allowed;
      opacity: 0.6;
    }
  }

  .login-options {
    padding: 0 6vw;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 10px;
    margin-bottom: 40px;
  }
}

.agreement-module {
  width: 100%;
  font-size: 8px;
  color: #cdcdcd;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 2px;

  .circle {
    height: 12px;
    aspect-ratio: 1/1;
    border: 1px solid #cdcdcd;
    border-radius: 50%;
    margin-right: 2px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    cursor: pointer;
    transition: all 0.3s ease;

    &.active {
      background-color: #000;
      border-color: #000;
    }
  }

  span {
    color: #000;
  }
}

.password-dialog-content {
  padding: 20px 0;
}

.password-input-wrapper {
  position: relative;
  width: 100%;

  .password-dialog-input {
    width: 100%;
    padding: 10px 35px 10px 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    box-sizing: border-box;
    font-size: 14px;
    outline: none;

    // 隐藏浏览器默认的密码显示按钮
    &[type="password"] {
      &::-webkit-credentials-auto-fill-button {
        display: none !important;
        visibility: hidden;
        pointer-events: none;
        opacity: 0;
        position: absolute;
        right: -9999px;
      }

      &::-webkit-strong-password-auto-fill-button {
        display: none !important;
        visibility: hidden;
        pointer-events: none;
        opacity: 0;
        position: absolute;
        right: -9999px;
      }

      // 针对 Edge 浏览器
      &::-ms-reveal {
        display: none !important;
      }

      &::-ms-clear {
        display: none !important;
      }
    }
  }

  .password-toggle-icon {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    cursor: pointer;
    font-size: 18px;
    color: #999;
  }
}
</style>
